package com.rxh.activeMQ;

import com.rxh.cache.BaseCache;
import com.rxh.exception.PayException;
import com.rxh.pojo.cross.BankResult;
import com.rxh.pojo.payment.MerchantNotify;
import com.rxh.service.MerchantNotifyService;
import com.rxh.service.PaymentNotifyService;
import com.rxh.utils.HttpClientUtils;
import com.rxh.utils.StringUtils;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.jms.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 陈俊雄
 * Date: 2018/9/21
 * Time: 10:03
 * Project: Management
 * Package: com.rxh.activeMQ
 */
public class ConsumerMessageListener implements MessageListener {
    public final static String MERCHANT_NOTIFY = "merchantNotify";
    public final static String ORDER_NOTIFY = "orderNotify";

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private MerchantNotifyService merchantNotifyService;

    @Autowired
    private PaymentNotifyService paymentNotifyService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onMessage(Message message) {
        try {
            Destination jmsDestination = message.getJMSDestination();
            if (jmsDestination instanceof ActiveMQTopic) {
                TextMessage textMessage = (TextMessage) message;
                BaseCache baseCache = applicationContext.getBean(textMessage.getText(), BaseCache.class);
                baseCache.cleanCache();
                baseCache.refreshCache();
                logger.info("刷新缓存：" + textMessage.getText() + "成功！");
            } else if (jmsDestination instanceof ActiveMQQueue) {
                ActiveMQQueue activeMQQueue = (ActiveMQQueue) jmsDestination;
                ActiveMQObjectMessage objectMessage = (ActiveMQObjectMessage) message;
                switch (activeMQQueue.getQueueName()) {
                    case ORDER_NOTIFY:
                        orderNotifyHandle(objectMessage);
                        break;
                    case MERCHANT_NOTIFY:
                        sendMerchantNotify(objectMessage);
                        break;
                    default:
                        break;
                }

            }
        } catch (JMSException e) {
            logger.error("ActiveMQ异常", e);
        }
    }

    private void orderNotifyHandle(ActiveMQObjectMessage objectMessage) {
        try {
          BankResult bankResult = (BankResult) objectMessage.getObject();
            paymentNotifyService.updateOrderAndDoNotify(bankResult);
        } catch (JMSException e) {
            logger.error("ActiveMQ异常", e);
        } catch (PayException e) {
            logger.error("ActiveMQ更新订单异常", e);
        }
    }

    private void sendMerchantNotify(ActiveMQObjectMessage objectMessage) {
        try {
            MerchantNotify merchantNotify = (MerchantNotify) objectMessage.getObject();
            Map<String, String> contentMap = BeanUtils.describe(merchantNotify);
            contentMap.remove("class");
            contentMap.remove("notifyTimes");
            contentMap.remove("notifyCycle");
            logger.info("通知商户参数：" + contentMap.toString());
            String result = HttpClientUtils.doPost(HttpClientUtils.getHttpsClient(), merchantNotify.getNotifyUrl(), contentMap);
            // 通知返回结果为空或不含有“Succeed”字符则重新通知
            if (StringUtils.isBlank(result) || StringUtils.containsIgnoreCase(result, MerchantNotifyService.SUCCEED)) {
                logger.warn("通知商户失败！" + "剩余通知商户次数：" + merchantNotify.getNotifyTimes());
                // 判断是否超过最大通知次数
                if (merchantNotify.getNotifyTimes() > 0) {
                    merchantNotify.setNotifyTimes(merchantNotify.getNotifyTimes() - 1);
                    merchantNotifyService.resendMerchantNotify(merchantNotify);
                }
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            logger.error("BeanUtils异常", e);
        } catch (JMSException e) {
            logger.error("ActiveMQ异常", e);
        }
    }
}